﻿using System.Collections.Generic;
using System.IO;

namespace Utility
{
    public static class EnumerableExtensions
    {
        public static Stream ToCsv(this IEnumerable<IEnumerable<string>> data)
        {
            var ms = new MemoryStream();
            var wr = new StreamWriter(ms);
            foreach (var line in data)
            {
                bool needComma = false;
                foreach (var field in line)
                {
                    if (needComma)
                        wr.Write(",");
                    else
                        needComma = true;
                    wr.Write(field.ToSafeCsvString());
                }
                wr.WriteLine();
            }
            wr.Flush();

            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
    }
}
